const Topic = require("../models/topic");
const TopicCategory = require("../models/topicCategory");
const collectService = require("./collectService");

//获取话题列表，按分类划分
exports.getList = async function(){
    //获取话题的列表
    const category = await TopicCategory.findAll({
        order:[['sort','ASC']]
    });
    let knowLedgeList =  [];
    let length = category.length;
    if(length > 0){
        for(let i=0;i<category.length;i++){
            let tempObj = {};
            tempObj.id = category[i].id;
            tempObj.name = category[i].name;
            tempObj.topics = await Topic.findAll({
                where:{ topicCategoryId: category[i].id},
                attributes:['id','title','img','content','publishDate','readNum'],
                order:[['readNum','DESC']]
            });
            knowLedgeList.push(tempObj);
        }
    }

    return {
        category,
        knowLedgeList
    }
    
}

//获取话题详情
exports.getDetail = async function(id,userId){
    let topic = await Topic.findOne({
        where:{id},
        attributes:['id','title','img','content','publishDate','readNum']
    });
    topic.readNum += 1;
    await topic.save();
    topic.readNum -= 1;
    topic.dataValues.isCollect = await collectService.isCollect(userId,id,'topic');
    return topic
}

